package com.hytech.licenseplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;



public class LicenseDbAdapter {

	// is this one checked. 
    public static final String KEY_CHECK = "isChecked";
    // what is the name of them.
    public static final String KEY_NAME = "plateName";
    public static final String KEY_ROWID = "_id";

    // for logging info. 
    private static final String TAG = "LicenseDbAdapter";
    
    // we need a database helper to manipulate the database. 
    private DatabaseHelper mDbHelper;

    // and this our database. 
    private SQLiteDatabase mDb;

    
    /**
     * These are the names and table of the database. 
     */
    private static final String DATABASE_NAME = "licenses";
    private static final String DATABASE_TABLE = "licenseplate";


    /**
     * Database creation sql statement
     *  "create table licenseplate (_id integer primary key autoincrement, "
     *  "isChecked integer default 0, plateName text not null);";
     *  But we'll use defines, to make sure we don't make a mistake. 
     */
    private static final String DATABASE_CREATE =
    	"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
    	+ KEY_CHECK + " integer default 0, " + KEY_NAME + " text not null);";

    private static final int DATABASE_VERSION = 3;
    private static final String DATABASE_DROP = 
    	"DROP TABLE IF EXISTS" + DATABASE_NAME;

    private final Context mCtx;
    
    
    private static class DatabaseHelper extends SQLiteOpenHelper {
    	
    	Context mCurrentContext;
    	SQLiteDatabase mDatabase;

    	
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            mCurrentContext = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
            mDatabase = db;
            loadInitialStateList();
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL(DATABASE_DROP);
            onCreate(db);
        }
        
        /**
         * load the database table with states.
         */
        private void loadInitialStateList() {
        	loadTargetStateList(0);
        }
        

        // this loads a target list of states.  
        public void loadTargetStateList(int whichStateList) {
        	// if this hasn't been defined yet we need to get it. 
        	if(mDatabase == null) { 
        		// I believe we need to grab the writable database. 
        		mDatabase = getWritableDatabase();
        	}
        		
        	try {
        		loadStates(whichStateList);
    		} catch (IOException e) {
    			throw new RuntimeException(e);
        	}
        
        }

        // this loads States from the list of states.  It can load
        // one of the lists in the file, however that's not currently set up. 
        private void loadStates(int whichStateList) throws IOException {
            Log.d(TAG, "Loading states...");
            final Resources resources = mCurrentContext.getResources();
            // we're using an input stream to get the resource. 
            InputStream inputStream = resources.openRawResource(R.raw.licenselists);
            // and now we can make it a simple buffered reader. 
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            int currentStateList = -1;
            try {
                String nextState;
                while ((nextState = reader.readLine()) != null) {
                	
                	// is this a new list. 
                	if ( nextState.charAt(0) == '#' ) {
                		currentStateList++;
                		// have we already read in the new state list. 
                		if ( currentStateList > whichStateList) {
                			break;
                		}
                		continue;
                	}
                	
                	// If I remove the list system ever or if this is the target list. 
                	if ( currentStateList == -1 || currentStateList == whichStateList ){
                
                		// add this state. 
                		long id = addSingleState(nextState.trim());
                    	if (id < 0) {
                    		Log.e(TAG, "unable to add state: " + nextState.trim());
                    	}
                	}
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Log.d(TAG, "DONE loading words.");
        }

        /**
         * Add a word to the dictionary.
         * @return rowId or -1 if failed
         */
        public long addSingleState(String stateName) {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_NAME, stateName);
            
            initialValues.put(KEY_CHECK, 0);
            
            return mDatabase.insert(DATABASE_TABLE, null, initialValues);
        }

    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public LicenseDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the license plate database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public LicenseDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    /**
     * Close the database when we are absolutely done with it.  
     */
    public void close() {
        mDbHelper.close();
    }


    /**
     * Return a Cursor over the list of all the plates we want to find.  
     * The State of the game if you will. 
     * 
     * @return Cursor over all states
     */
    public Cursor fetchCurrentState(boolean includeCheckedRows) {

        if ( includeCheckedRows ) {
        	return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CHECK,
         			KEY_NAME}, null, null, null, null, null);
        } else {
        	return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CHECK,
        			 KEY_NAME}, KEY_CHECK + " = 0", null, null, null, null);
        }
        
    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateNote(long rowId, boolean isChecked) {
        ContentValues args = new ContentValues();
        args.put(KEY_CHECK, isChecked);
        
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    // This should delete all the records in the database.
    public int clearDatabase() {
        
        return mDb.delete(DATABASE_TABLE, null, null);
    }
    
    // this is a pass through function which will load a target list. 
    public void loadTargetList(int whichList) {
    	 mDbHelper.loadTargetStateList(whichList);
    	 
    }
    
    public int getTotalRecords() {
    	Cursor recordCount = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID}, null, null, null, null, null);
    	return recordCount.getCount();
    }
    
    public int getSelectedRecords() {
    	Cursor recordCount = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID}, KEY_CHECK + " = 1", null, null, null, null);
    	return recordCount.getCount();
    }
    
}
